package controller;

import entity.Emp;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/validate")
public class ValidateController {


    @RequestMapping("/show")
    public String show(Emp emp){
        System.out.println("ValidateController.show()");
        return "validate";
    }

    
    @RequestMapping("/submit")
    public String submit(@Valid Emp emp, Errors errors,Map map){
        System.out.println("ValidateController.submit()");

        if(errors.hasErrors()){
            Map<String,String> errorMap=new HashMap<String,String>();

            List<FieldError> fieldErrors=errors.getFieldErrors();

            for (FieldError fieldError : fieldErrors) {
                System.out.println("fieldError = " + fieldError);

                System.out.println("fieldError.getRejectedValue() = " + fieldError.getRejectedValue());
                System.out.println("fieldError.getCode() = " + fieldError.getCode());
                System.out.println("fieldError.getObjectName() = " + fieldError.getObjectName());
                System.out.println("fieldError.getField() = " + fieldError.getField());
                System.out.println("fieldError.getDefaultMessage() = " + fieldError.getDefaultMessage());

                errorMap.put(fieldError.getField(), fieldError.getDefaultMessage());
            }

            map.put("errors",errorMap);

            return "validate";
        }


        System.out.println(emp);

        return "redirect:/validate/show";
    }
}
